/**
 * PopoForm.open 方法返回的事件对象
 */
function PopoEvent(popoForm) {
  var ins = this;

  this.popoForm = popoForm;
  this._event = {};

  /**
   * 添加事件
   * @param {string} key
   * @param {function} fun
   */
  this.on = function(key, fun) {
    if (this._event[key] == null) {
      this._event[key] = [];
    }
    this._event[key].push(fun);
  };

  /**
   * 添加事件，但保证不会重复添加同样的函数
   * @param {string} key
   * @param {function} fun
   */
  this.unique = function(key, fun) {
    var events = this._event[key] || [];
    var found = events.find(item => {
      return item.toString() == fun.toString();
    });

    if (!found) {
      this.on(key, fun);
    }
  };

  var invokeFun = (funs, args) => {
    funs.forEach(fun => {
      try {
        fun.apply(this, args);
      } catch ($e) {
        console.error("PopoCallable", "invokeFun", $e);
      }
    });
  };

  this.trigger = function() {
    var args = Array.prototype.slice.apply(arguments);
    var key = args.shift();
    var events = ins._event[key] || [];
    invokeFun(events, args);
  };

  this.success = function(fun, append) {
    ins.unique("success", fun);
    return this;
  };
  this.fail = function(fun) {
    ins.unique("fail", fun);
    return this;
  };
  this.complete = fun => {
    ins.unique("complete", fun);
    return this;
  };
  this.cancel = fun => {
    ins.unique("cancel", fun);
    return this;
  };
  this.edit = func => {
    ins.unique("edit", func);
    return this;
  };
  this.close = func => {
    ins.unique("close", func);
    return this;
  };

  this.clear = () => {
    ins._event = {};
  };

  // this.callSuccess = function(){
  //     this.trigger( Array.prototype.slice.apply(arguments).unshift( "success") );
  //     invokeFun( ins._successFun, );
  // }
}

export default PopoEvent;
